<script lang="ts" setup>
  import { ElSelect } from 'element-plus'
  import { getList } from '@/api/userManagement'

  const props = defineProps({
    ...ElSelect.props,
    modelValue: {
      type: String,
      default: '',
    },
    keywords: {
      // 搜索条件
      type: String,
      default: '',
    },
    immediateLoad: {
      // 是否立即加载数据
      type: Boolean,
      default: false,
    },
    data: {
      type: Array,
      default: () => {
        return []
      },
    },
  })
  const emits = defineEmits(['update:modelValue'])
  const userVal = ref('')
  const user = reactive({
    list: [],
  })

  const handleUserChange = (val) => {
    emits('update:modelValue', val)
  }

  const getUserList = async () => {
    const params = {
      pageNum: 1,
      pageSize: 9999,
    }
    if (props.keywords) {
      params.keywords = props.keywords
    }
    const {
      data: { list },
    } = await getList(params)
    user.list = list || []
  }

  onMounted(() => {
    if (props.immediateLoad) {
      // eslint-disable-next-line
      props.filterable = true
      getUserList()
    } else if (props.data && props.data.length > 0) {
      user.list = props.data
    }
  })
</script>

<template>
  <el-select v-model="userVal" v-bind="props" @change="handleUserChange">
    <el-option
      v-for="item in user.list"
      :key="item.id"
      :label="item.nickname"
      :value="item.id"
    />
  </el-select>
</template>
